/*******
 *
 * 主要包括表单中，引用表格（关联数据 / 关联查询）所用到的处理函数
 *
 *******/
import { FormComponentKey } from '@/enums/componentKey';
import {
  getDifferenceArray,
  merge,
} from '@/utils/index';
import {
  isNullOrEmpty,
  isNullOrUnDef,
  isObject,
  isEmpty,
} from '@/utils/is';

// 获取过滤条件的运行结果
export function getFilterCondition(
  conditionTree,
  fieldTypeMap,
  fieldKeyMap,
  formState,
  formFormat,
) {
  const { operator, children, expression } = conditionTree;

  if (children && children.length) {
    const results = [];
    for (const treeNode of children) {
      // 递归处理
      const result = getFilterCondition(treeNode, fieldTypeMap, fieldKeyMap, formState, formFormat);
      results.push(result);
      if (operator === 'AND' && result === false) {
        return false;
      }
    }
    if (operator === 'AND' && results.every((item) => item)) {
      return true;
    }
    if (operator === 'OR') {
      if (results.some((item) => item)) {
        conditionTree.children = conditionTree.children.filter((item, index) => results[index]);
        return true;
      } else {
        return false;
      }
    }
  } else if (expression) {
    const { value: conditionValue } = expression.filterCondition;
    if (conditionValue && conditionValue.valueType) {
      const { valueType, value } = conditionValue;
      if (valueType === 'DYNAMIC') {
        const componentKey = fieldTypeMap[value];
        switch (componentKey) {
          case FormComponentKey.AntdSelectFormPc:
          case FormComponentKey.AntdTreeSelectFormPc:
          case FormComponentKey.AntdRadioGroupFormPc:
            expression.filterCondition.value = formFormat.getLabelByValue(
              `${fieldKeyMap[value]}_options`,
              formState[value],
              value,
            );
            break;
          case FormComponentKey.AntdDatePickerFormPc:
          case FormComponentKey.AntdRangePickerFormPc:
            expression.filterCondition.value = formFormat.getMixedTypeLabelValue(
              value,
              formState[value],
            );
            break;
          default:
            expression.filterCondition.value = formState[value];
            break;
        }
        if (!expression.filterCondition.value) {
          return false;
        }
      } else if (valueType === 'FIXED') {
        expression.filterCondition.value = value;
      }
    }
  }
  return true;
}
// 组装格式化表格数据
export function formatDataList(dataList, subFormList) {
  const resultDataList = []; // 输出的数据
  dataList.forEach((formData, dataIndex) => {
    const rowInfo = {
      rowSpan: 1,
      rowList: [],
    };
    let dataItem = {};
    let subformFieldList = []; // 子表单字段列表

    const additionRowList = []; // 子表单额外增加的列
    //  子表单数据格式化
    Object.keys(formData).forEach((item) => {
      // 暂时不对children数据进行处理
      if (item !== 'children') {
        const filedValue = formData[item];
        // 如果是对象，可认为是子表单(地址组件也可能是对象)
        if (isObject(filedValue) && subFormList.includes(item)) {
          const { dataList: subformDataList } = filedValue;
          if (isNullOrEmpty(subformDataList)) {
            return;
          }
          // 获取需要合并的单元的最大值
          subformDataList.length > rowInfo.rowSpan && (rowInfo.rowSpan = subformDataList.length);
          // 遍历数据拆分成表格需要的数据
          subformDataList.forEach((subformDataItem, index) => {
            //  提取出id，避免合并时覆盖掉主数据
            const { id, ...pureData } = subformDataItem;
            if (index === 0) {
              // 第一项数据合并到当前的的行中
              // 记录子表单的所有字段，取并集
              subformFieldList = Array.from(
                new Set(subformFieldList.concat(Object.keys(pureData))),
              );
              merge(dataItem, pureData);
            } else {
              // 其他数据放到新行中
              (isNullOrUnDef(additionRowList[index - 1]) || isEmpty(additionRowList[index - 1])) &&
                (additionRowList[index - 1] = { id: pureData.page_id + '_' + id }); // 新行初始化为一个空对象，id为拼接id，避免重复
              merge(additionRowList[index - 1], pureData);
            }
          });
          dataItem[item] = filedValue;
        } else if (isNullOrUnDef(dataItem[item])) {
          // dataItem中没有这一个数据，就推进去
          // 需要合并的单元格
          rowInfo.rowList.push(item);
          dataItem[item] = dataItem[item] ? dataItem[item] : filedValue;
        }
      } else {
        dataItem[item] = formData[item];
      }
    });
    // 与子表单中的所有字段取差集，保证没有额外的合并元素
    rowInfo.rowList = getDifferenceArray(rowInfo.rowList, subformFieldList);
    // 处理附加到行合并信息
    dataItem['__ADDITION_ROW_INFO'] = rowInfo;
    // 增加key字段，以适应表格选择行为
    if (!dataItem.hasOwnProperty('key')) {
      dataItem['key'] = dataItem.id;
    }
    // 推入处理完的数据
    resultDataList.push(dataItem);
    // 合并增加额外的列，并附加上额外的信息
    additionRowList.length > 0 &&
      resultDataList.push(
        ...additionRowList.map((item) => {
          item['__ADDITION_ROW_INFO'] = {
            ...rowInfo,
            extra: true,
          };
          return item;
        }),
      );
  });
  return resultDataList;
}

// 设置行合并
export function setCustomCell(record, rowIndex, column) {
  const { rowSpan, rowList, extra } = record.__ADDITION_ROW_INFO || {};
  // 原始单元格合并后，插入进来的行隐藏该单元格
  if (extra && ['sequenceNumber', 'operation'].concat(rowList).includes(column.dataIndex)) {
    return { rowSpan: 0 };
  }
  // 合并单元格
  if (['sequenceNumber', 'operation'].concat(rowList).includes(column.dataIndex)) {
    return { rowSpan: rowSpan };
  }
  return { rowSpan: 1 };
}

// 递归表头
export function recursionColumn(columnList) {
  return columnList.map((item) => {
    item.customCell = setCustomCell;
    if (item.children && item.children.length > 0) {
      item.children = recursionColumn(item.children);
    }
    return item;
  });
}
